import EventManager from './event.js';
import AudioManager from './audio.js';

class ListenerManager {
    constructor() {
        this.listenerMap = new Map();
        this.keyStates = new Map();
        this.setupEventListeners();
    }

    setupEventListeners() {
        this.setupMouseEvents();
        this.setupKeyboardEvents();
    }

    setupMouseEvents() {
        const clickHandler = async (e) => {
            await AudioManager.playBGM();
            EventManager.emit('mouse_click', e);
        };

        window.addEventListener('click', clickHandler);
        this.listenerMap.set('click', clickHandler);
    }

    setupKeyboardEvents() {
        const keydownHandler = (e) => {
            if (this.keyStates.get(e.code)) return;
            
            this.keyStates.set(e.code, true);
            
            switch(e.code) {
                case 'Space':
                case 'ArrowUp':
                    EventManager.emit('mario_jump');
                    break;
                case 'ArrowLeft':
                    EventManager.emit('mario_move_left');
                    break;
                case 'ArrowRight':
                    EventManager.emit('mario_move_right');
                    break;
            }
            
            EventManager.emit('keydown', e);
        };

        const keyupHandler = (e) => {
            this.keyStates.set(e.code, false);
            
            switch(e.code) {
                case 'ArrowLeft':
                    EventManager.emit('mario_stop_left');
                    break;
                case 'ArrowRight':
                    EventManager.emit('mario_stop_right');
                    break;
            }
            
            EventManager.emit('keyup', e);
        };

        window.addEventListener('keydown', keydownHandler);
        window.addEventListener('keyup', keyupHandler);
        
        this.listenerMap.set('keydown', keydownHandler);
        this.listenerMap.set('keyup', keyupHandler);
    }

    addMouseListener(eventType, callback) {
        window.addEventListener(eventType, callback);
        this.listenerMap.set(eventType, callback);
    }

    addKeyboardListener(eventType, callback) {
        window.addEventListener(eventType, callback);
        this.listenerMap.set(eventType, callback);
    }
    
    removeListener(eventType) {
        const callback = this.listenerMap.get(eventType);
        if (callback) {
            window.removeEventListener(eventType, callback);
            this.listenerMap.delete(eventType);
        }
    }

    isKeyPressed(keyCode) {
        return this.keyStates.get(keyCode) || false;
    }

    clearListeners() {
        this.listenerMap.forEach((callback, eventType) => {
            window.removeEventListener(eventType, callback);
        });
        this.listenerMap.clear();
        this.keyStates.clear();
    }

    destroy() {
        this.clearListeners();
    }
}

export default ListenerManager;